package com.photoeditor.demo.app;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.common.base.ComponentContext;
import com.common.base.utils.thread.ThreadPool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class TestUser {
        private static final String TEST_FILE = "superAdTestUser";
        private static boolean[] sTestUser;
        private static String sTestStrategy = null;
        private static String sTestMediaSource = null;
        private static Map<String, String> mConfigs;
        private static boolean sAdTest;

        public static File getTestFile() {
            File file = null;
            try {
                // superTestUser
                int[] chrs = new int[]{115, 117, 112, 101, 114, 84, 101, 115, 116, 85, 115, 101, 114};
                String testFile = "";
                for (int c : chrs) {
                    testFile += (char) c;
                }
                file = new File(Environment.getExternalStorageDirectory(), testFile);
            } catch (Throwable err) {
            }
            if (file != null && file.exists() && file.isFile()) {
                return file;
            }
            return null;
        }

        public static File getDataTestFile() {
            File file = null;
            try {
                // superTestUser
                int[] chrs = new int[]{115, 117, 112, 101, 114, 84, 101, 115, 116, 85, 115, 101, 114};
                String testFile = "";
                for (int c : chrs) {
                    testFile += (char) c;
                }
                file = new File(Environment.getExternalStorageDirectory() + "/Android/data/" + ComponentContext.getPackageName(), testFile);
            } catch (Throwable err) {
                err.printStackTrace();
            }
            if (file != null && file.exists() && file.isFile()) {
                return file;
            }
            return null;
        }

        public static File getAdTestFile() {
            File file = null;
            try {
                file = new File(Environment.getExternalStorageDirectory(), TEST_FILE);
            } catch (Throwable err) {
            }
            if (file != null && file.exists() && file.isFile()) {
                return file;
            }
            return null;
        }

        public static boolean isTestUser() {
            if (sTestUser != null) {
                return sTestUser[0];
            }
            ThreadPool.runOnNonUIThread(new Runnable() {
                @Override
                public void run() {
                    synchronized (TestUser.class) {
                        if (sTestUser == null) {
                            if (Looper.myLooper() == null) {
                                try {
                                    Looper.prepare();
                                } catch (Exception e) {
                                    return;
                                }
                            }
                            boolean testUser = initTestUserInfo(ComponentContext.getContext());
                            sTestUser = new boolean[1];
                            sTestUser[0] = testUser;
                        }
                    }
                }
            });
            return false;
        }

        /**
         * "media_source=xxxxx", media_source如果不设置，则不发送广播，
         * 如果media_source=，则发送google（自然），
         * 如果为media_source=xxx，则发送xxx广播
         * "strategy={}"，对应策略信息，会写重写配置信息
         *
         * @return
         */
        private static boolean initTestUserInfo(Context context) {
            File file;
            if (ContextCompat.checkSelfPermission(ComponentContext.getContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                file = getDataTestFile();
            } else {
                file = getTestFile();
            }
            if (file == null) {
                return false;
            }
            File adFile = getAdTestFile();
            sAdTest = adFile != null;
            mConfigs = new HashMap<>();
            boolean ret = false;
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(file));
                String line = null;
                while ((line = br.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("#") || TextUtils.isEmpty(line)) {
                        continue;
                    }
                    String[] cols = TextUtils.split(line, "\\s*=\\s*");
                    if (cols != null && cols.length == 2) {
                        mConfigs.put(cols[0].trim(), cols[1].trim());
                        if (TextUtils.equals("media_source", cols[0])) {
                            String info;
                            if (TextUtils.isEmpty(cols[1]) || "google".equalsIgnoreCase(cols[1])
                                    || "google-play".equalsIgnoreCase(cols[1])) {
                                info = "test:user, default channel:google";
                                sTestMediaSource = "google";
                            } else {
                                info = "test:user(" + cols[1] + ")";
                                sTestMediaSource = cols[1];
                            }
                            Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
                        } else if (TextUtils.equals("strategy", cols[0])) {
                            if (!TextUtils.isEmpty(cols[1])) {
                                try {
                                    JSONObject jsonObject = new JSONObject(cols[1]);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(context, "strategy test error：" + e.toString(), Toast.LENGTH_LONG).show();
                                    continue;
                                }
                                sTestStrategy = cols[1];
//                                SPUtils.put(context, SPUtils.SDK_STRATEGY_CONTROL_INFO, sTestStrategy);
//                                Toast.makeText(context, "策略设置成功", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }
                ret = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(context, "test error：" + e.toString(), Toast.LENGTH_LONG).show();
                ret = false;
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(context, "test error：" + e.toString(), Toast.LENGTH_LONG).show();
                ret = false;
            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(context, "test error：" + e.toString(), Toast.LENGTH_LONG).show();
                ret = false;
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    br = null;
                }
            }
            return ret;
        }

        public static boolean isAdTest() {
            return sAdTest;
        }

        public static void refreshFile() {
            initTestUserInfo(ComponentContext.getContext());
        }

        public static @Nullable
        String getValue(@NonNull String key) {
            return mConfigs != null ? mConfigs.get(key) : null;
        }

        public static boolean getBooleanValue(@NonNull String key, boolean defValue) {
            String value = getValue(key);
            if (TextUtils.equals(value, "false")) {
                return false;
            } else if (TextUtils.equals(value, "true")) {
                return true;
            }
            return defValue;
        }

        public static String getTestBuyUserUtmSrouce() {
            return sTestMediaSource;
        }


    }